08 / 16

Explain the difference between `fs.readFile()` and `fs.createReadStream()` for reading files in Node.js.

  1. 1

    fs.readFile() reads the entire file into memory and then invokes the callback with the file's contents. It's suitable for small files but can be memory-intensive for large files.

  2. 2

    fs.createReadStream() reads the file in smaller chunks (buffers) and allows for streaming the file's contents. It's more memory-efficient and suitable for handling large files.

Difficulty: 3/10
Topics: file I/O, streaming, memory usage

Scenario Questions

0-2 years experience
  1. 1

    We need to load a 5 KB JSON config file and send its contents in an HTTP response. Which fs API would you pick and why?

  2. 2

    If you used fs.createReadStream to read a tiny text file, what would happen compared to using fs.readFile?

2-5 years experience
  1. 1

    A new feature processes user‑uploaded CSV files. It works for files under 1 MB but crashes on larger ones. How would you debug the problem and decide between readFile and createReadStream?

  2. 2

    During a code review you see a teammate using fs.readFile to pipe data into a network socket. What concerns would you raise and what alternative would you suggest?

5-8 years experience
  1. 1

    Our video‑streaming service serves large files to many clients simultaneously. Explain how using fs.createReadStream versus fs.readFile impacts back‑pressure handling and memory usage under high concurrency.

  2. 2

    Design the I/O layer for a log‑aggregation pipeline that reads huge log files, transforms each line, and writes to a remote store. How would you use streams to ensure scalability and fault tolerance?

8+ years experience
  1. 1

    We are migrating a legacy batch job that reads multi‑gigabyte data dumps to a microservice architecture. Discuss the trade‑offs of keeping fs.readFile in some components versus moving everything to streaming, considering deployment, observability, and team ownership.

  2. 2

    Multiple services in our organization have mixed usage of readFile and createReadStream for similar tasks, causing inconsistent performance. How would you create a company‑wide guideline and migration plan while balancing risk, testing, and backward compatibility?

Follow-up Questions

  • What are the memory implications of using readFile versus a stream?
  • How does back‑pressure affect a read stream in a high‑throughput scenario?
  • Can you sketch a short code example that pipes a read stream into an HTTP response?